﻿using Common;
using Common.EF.Controllers;
using Common.Model;
using Common.Models;
using Common.Utility;
using Common.Utility.AJ;
using FluentValidation;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AWSV2.ViewModels
{
    public class CustomerDetailViewModel : AnnotationValidationScreen<Customer>
    {
        private string _title;
        public string Title
        {
            get => _title;
            set => SetAndNotify(ref _title, value);
        }

        private AJErrorInfoDialogParams _errorInfo;
        public AJErrorInfoDialogParams ErrorInfo
        {
            get => _errorInfo;
            set => SetAndNotify(ref _errorInfo, value);
        }

        private bool _addMode;
        public bool AddMode
        {
            get => _addMode;
            set => SetAndNotify(ref _addMode, value);
        }

        private bool _loading;
        public bool Loading
        {
            get => _loading;
            set => SetAndNotify(ref _loading, value);
        }

        private Customer _form;
        public override Customer Form
        {
            get => _form;
            set => SetAndNotify(ref _form, value);
        }

        public CustomerDetailViewModel(Customer form = null)
        {
            ErrorInfo = new AJErrorInfoDialogParams();

            AddMode = form == null;
            Title = AddMode
                ? I18NService.Translate(LangKeys.新增, I18NService.Translate(LangKeys.客户))
                : I18NService.Translate(LangKeys.编辑_0_, form.Name);
            _form = new Customer();
            if (form != null)
            {
                AJUtil.CopyPropertyValues(_form, form);
            }

        }

        private bool _canCommit;
        public bool CanCommit
        {
            get
            {
                _canCommit = !Loading;
                return _canCommit;
            }
            set => SetAndNotify(ref _canCommit, value);
        }
        public async void Commit()
        {
            if (!ValidateModel())
            {
                ErrorInfo.Show(string.Join("\r\n", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString())));
                return;
            }

            Loading = true;
            try
            {
                using var ctrl = new CustomerController();
                var result = await ctrl.Save(AJAutoMapperService.Instance()
                    .Mapper.Map<Customer, Common.EF.Tables.Customer>(_form));

                RequestClose(true);
            }
            catch (Exception e)
            {
                ErrorInfo.Show(e.Message);
            }
            finally
            {
                Loading = false;
            }
        }
    }
}
